





package com.lanou3g.springcloud.consumer.hystrix.web;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;

/**
 * Eureka服务注册中心常规调用方式
 */
@Slf4j
@Controller
@RequestMapping("/ribbon")
public class HelloRibbonController {

	@Autowired
	private RestTemplate restTemplate;

	@HystrixCommand(fallbackMethod = "defaultHelloFallback")
	@RequestMapping("/")
	public String defaultHello(Model model) {
		String url = "http://hello-server/";
		String result = restTemplate.getForObject(url, String.class);
		model.addAttribute("msg", result);
		return "index";
	}

	public String defaultHelloFallback(Model model) {
		model.addAttribute("msg", "[FB] Hello SpringCloud!");
		return "index";
	}

	@HystrixCommand(fallbackMethod = "nameHelloFallback")
	@RequestMapping("/name/{name}")
	public String nameHello(@PathVariable String name, Model model) {
		String url = "http://hello-server/name/"+name;
		String result = restTemplate.getForObject(url, String.class);
		model.addAttribute("msg", result);
		return "index";
	}

	public String nameHelloFallback(String name, Model model) {
		log.warn("hello-server的nameHello接口挂了，将返回降级内容");
		model.addAttribute("msg", "[FB] Hello, " + name);
		return "index";
	}

	@RequestMapping("/json/{name}")
	public String jsonHello(@PathVariable String name, Model model) {
		String url = "http://hello-server/json/"+name;
		String result = restTemplate.getForObject(url, String.class);
		model.addAttribute("msg", result);
		return "index";
	}
}